//
//  QRCodeViewController.swift
//  Weibo
//
//  Created by 浦源 on 16/4/24.
//  Copyright © 2016年 Lizhuo. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {
    
    @IBOutlet weak var scanLineCons: NSLayoutConstraint!
    @IBOutlet weak var containerHeightCons: NSLayoutConstraint!
        /// 冲击波
    @IBOutlet weak var scanLineView: UIImageView!
    //底部视图
    @IBOutlet weak var customTabBar: UITabBar!
    
    @IBAction func closeBtnClick(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.设置底部视图默认选中第0个
        customTabBar.selectedItem = customTabBar.items![0]
        customTabBar.delegate = self
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //1.开始冲击波动画
        startAnimation()
        
        //2.开始扫描
        startScan()
    }
    
    /**
     扫描二维码
     */
    private func startScan() {
        //1.判断是否
    }
    
    private func startAnimation() {
        //让约束从顶部开始
        scanLineCons.constant = -containerHeightCons.constant
        scanLineView.layoutIfNeeded()
        
        //执行冲击波的动画
        UIView.animateWithDuration(5.0, animations: {
            //1.修改约束
            self.scanLineCons.constant = self.containerHeightCons.constant
            //设置动画指定的次数
            UIView.setAnimationRepeatCount(MAXFLOAT)
            //2.强制更新界面
            self.scanLineView.layoutIfNeeded()
        })
    }
    
    //MARK: － 懒加载
    //会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    //拿到输入设备
    private lazy var deviceInput: AVCaptureDeviceInput? = {
        //获取摄像头
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do {
            // 创建输入对象
            let input = try AVCaptureDeviceInput(device: device)
            return input
        } catch {
            print(error)
            return nil
        }
    }()
    
    // 拿到输入对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
}

extension QRCodeViewController: UITabBarDelegate {
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        //1.修改容器的高度
        if item.tag == 1 {
            containerHeightCons.constant = 300
        } else {
            containerHeightCons.constant = 150
        }
        
        //2.停止动画
        scanLineView.layer.removeAllAnimations()
        
        //3.重新开始动画
        startAnimation()
    }
}
